#
# cpanel.py - handlers for control panel page of the application
#
# Copyright 2008-2009 Autelic Association (http://www.autelic.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi, sys, os, logging, string
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
import wsgiref.handlers


import atom.url
import gdata.service
import gdata.alt.appengine
import gdata.contacts
import gdata.contacts.service
import gdata.photos.service
import urllib # Used to unescape URL parameters.

# Import our own modules
from constants import *
import loggedin.profile
import pages

####### role box
class role_box:
  def __init__(self, name, message='', form_action='', button_name=''):
     # store these general value about the whole box
     self.role_name = name
     # start the html, and add the role box name
     self.html = '<div class="role_box"><div class="role_box_title">' + name + '</div><br> '
     # add the message
     if message:
        self.html = self.html + message + ' <br>'

     if form_action:
        self.html = self.html + '<form action="/in/cpanel?action=' + form_action + '"' + ' enctype="multipart/form-data" method="post"> <div><input type="submit" value="' + button_name + '"</div></form>'

  def add_message(self, message):
     self.html = self.html + message + ' <br>'

  def add_form(self, form_action, button_name):
     self.html = self.html + '<form action="/in/cpanel?action=' + form_action + '"' + ' enctype="multipart/form-data" method="post"> <div><input type="submit" value="' + button_name + '"</div></form>'

  def show(self):
     # close the HTML section and output it all
     self.html = self.html + ' </div>'
     return self.html

################################# cpanel class ###########################
class cpanel(webapp.RequestHandler):
  def contacts(self, user_email):
    client = gdata.contacts.service.ContactsService()
    gdata.alt.appengine.run_on_appengine(client)

    try:
       contacts = client.GetContactsFeed('http://www.google.com/m8/feeds/contacts/default/full').entry
    except:
       html = "Error accessing contacts for user %s" % user_email
       return html

    html = 'Contacts (%d):' % (len(contacts))
    email_count = 0

    if contacts:
       html = html + '<ul>'
       for contact in contacts:
         html = html + ('<li>%s' % (contact.title.text))
         if contact.content:
           html = html + ('    %s' % (contact.content.text))
         # Display the primary email address for the contact.
         for email in contact.email:
   #        if email.primary and email.primary == 'true':
           html = html + ('    %s' % (email.address))
           email_count = email_count + 1
         # Show the contact groups that this contact is a member of.
         for group in contact.group_membership_info:
           html = html + ('    Member of group: %s' % (group.href))
         # Display extended properties.
         for extended_property in contact.extended_property:
           if extended_property.value:
             value = extended_property.value
           else:
             value = extended_property.GetXmlBlobString()
           html = html + ('    Extended Property - %s: %s' % 
                          (extended_property.name, value))
         html = html + '</li>'
       html = html + ("</ul>%d e-mail addresses found" % email_count)

    return html

  def photo_albums(self, user_email, user_profile):
    # initialize a client to talk to Google Data API services
    client = gdata.photos.service.PhotosService()
    gdata.alt.appengine.run_on_appengine(client)  # run on App Engine

    try: # Attempt to fetch the feed of users own albums
      album_list = client.GetUserFeed(user=user_email).entry
    except:
      html = "Error accessing albums. Check user %s has a PicasaWeb account" % user_email
    else:
      html = 'Photos: User %s has %d viewable albums in Picasaweb and %d shared albums in their profile.<br>' % (user_email, len(album_list), len(user_profile.shared_albums))
      
    return html   

##### internal function (to cpanel class) to get profile
  def get_profile(self, page):
     # load user profile from the Datastore
     q = db.GqlQuery("SELECT * FROM Profile WHERE user = :1",
                    users.get_current_user())

     try:
        profile = q.get()
     except:
        #This is to catch some problems when running with a local datastore
        profile = None

     # if no profile for that user exists, then we make one. We always exit with a profile!
     if profile == None:              
         profile = loggedin.profile.Profile(user=users.get_current_user())
         try:
            db.put(profile)
         except:
            profile.photo = None

         page.add_message('Profile created for user %s' % users.get_current_user().email())

     # add the photo section of html to the page, which is either the photo itself
     # or a message explaining no photo is present and the user should add one using photo_form.
     if profile.photo == None:
        path = os.path.join(os.path.dirname(__file__), 'photo_form.html')
        template_values = { 'message': 'No photo present in your profile. Please add one.',}
        page.add_html(template.render(path, template_values))
     else:
         page.add_message("<img align='left' src='/in/photo?photo_id=%s'></img>" % profile.key())
     
     # TODO complete the rest of the profile, first and last name etc
     # and evantually set the 'complete' flag to True

     return profile


##############################################################################
##### get method for cpanel class
  def get(self):
    page = pages.Page('Control Panel')
    user_email = users.get_current_user().email()

    # get any error message passed on 'error_message' parameter
    error_message=self.request.get('error_message')
    if error_message:
       page.add_html('<div style="color: red">%s</div>' % error_message)

    # load the users profile data
    profile = self.get_profile(page)

    # Check if the user is an admin for this domain
    if users.is_current_user_admin():
       box = role_box('Role: Admin', 'User is admin')
       page.add_html(box.show())

    # check if the user is a tutor to any other user
    if not profile.tutored:
       text = 'You are not a tutor to any other user'
    else:
       text = 'names will go here'
    box = role_box('Role: Tutor', text, 
                   'add_student', 'Add student')
    page.add_html(box.show())

    # check if the user is tutored (i.e. a student) of any other user
    if not profile.tutors:
       text = 'You do not have any tutors'
    else:
       text = 'names will go here'
    box = role_box('Role: Student', text,
                   'add_tutor', 'Add tutor')
    page.add_html(box.show())

    box = role_box('Role: User')
    
    # Get list of current users contacts either from GMail or HOME_DOMAIN
    box.add_message(self.contacts(user_email))

    # Get list of current user's PUBLIC albums from Picasaweb
    box.add_message(self.photo_albums(user_email, profile))

    # add form to allow user to add a SharedAlbum
    path = os.path.join(os.path.dirname(__file__), 
                        'album_add_form.html')
    template_values = { 'album_error_message': self.request.get("album_error_message")}
    box.add_message(template.render(path, template_values))
           
    # add a link to allow user to open photo view URL in new window
    box.add_message('<a href="photo_view?user_key=%s" target="_blank" >View Photo Stream</a>' %
                    profile.key())

    # close the box
    page.add_html(box.show())

    self.response.out.write(page.show())

## End of 'cpanel'
############################################

####### Main
def main(argv):
  application = webapp.WSGIApplication(
    [('/in/cpanel', cpanel),],
    debug=True)
    
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main(sys.argv)
